package com.luis.toolsuite.isolationforest;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;

public final class IFUtils {

	private IFUtils() {}
	public static final int IF_SEED = 1;
	
	/**
     * 以某个值为界，随机生成某个数量的，不重复的随机数
     * @param random 随机
     * @param indexSize 随机数数量
     * @param bound 随机边界
     * @return 一组不重复的随机数
     */
	public static Integer[] getUniqueIndex(Random random, int indexSize, int bound) {
    	Set<Integer> indexSet = new LinkedHashSet<>();
    	while(indexSet.size() < indexSize) {
    		indexSet.add(random.nextInt(bound));
    	}
    	return indexSet.toArray(new Integer[indexSet.size()]);
    }
	
	/**判断样本是否单一数据*/
	public static boolean isSampleAllSame(double[][] samples) {
		boolean isAllSame = true;
		int rows = samples.length;
        int cols = samples[0].length;
        break_label:
        for (int i = 0; i < rows - 1; i++) {
            for (int j = 0; j < cols; j++) {
                if (samples[i][j] != samples[i + 1][j]) {
                    isAllSame = false;
                    break break_label;
                }
            }
        }
		return isAllSame;
	}
	
	//创建一个随机样本
	public static double[][] buildSample(int size, int featureNumber) {
		double[][] sample = new double[size][featureNumber];
		Random[] randomArr = new Random[featureNumber];
		//确保每个特征使用同一个随机种子
		for(int i=0;i<featureNumber;i++) {
			randomArr[i] = new Random(i);
		}
		for(int i=0;i<size;i++) {
			for(int j =0;j<featureNumber;j++) {
				sample[i][j] = randomArr[j].nextDouble();
			}
		}
		return sample;
	}
	
	//计算分位数
	public static double percentile(double[] data,double p){
		int n = data.length;
		Arrays.sort(data);
		double px =  p*(n-1);
		int i = (int) Math.floor(px);
		double g = px - i;
		if(g==0){
			return data[i];
		}else{
			return (1-g)*data[i]+g*data[i+1];
		}
	}
}
